/*
** timer.c for zappy in /home/guidet_m/TECK2/projets/zappy/server_zappy
** 
** Made by michael guidet
** Login   <guidet_m@epitech.net>
** 
** Started on  Mon Jul  4 15:35:24 2011 michael guidet
** Last update Mon Jul  4 15:35:29 2011 michael guidet
*/

#include "server.h"

int	calc_mintime(t_env *e)
{
  t_fd	*tmp;
  t_egg	*tmp2;
  int	timeout;
  int	i;

  timeout = 0;
  for (tmp = e->fd; tmp; tmp = tmp->next)
    {
      if (tmp->type == AI)
	{
	  if (!timeout)
	    timeout = tmp->pl->life;
	  if (timeout > tmp->wait && tmp->wait != -1)
	    timeout = tmp->wait;
	  if (timeout > tmp->pl->life)
	    timeout = tmp->pl->life;
	}
    }
  for (i = 0; e->teams[i].name; i++)
    for (tmp2 = e->teams[i].eggs; tmp2; tmp2 = tmp2->next)
      if (timeout > tmp2->time)
	timeout = tmp2->time;
  return ((timeout < 0) ? 0 : timeout);
}

long	timeval_to_int(struct timeval timeval)
{
  long	result;

  result = timeval.tv_sec * 1000000;
  result += timeval.tv_usec;
  return (result);
}

void	int_to_timeval(struct timeval *timeval, int time)
{
  timeval->tv_sec = time / 1000000;
  timeval->tv_usec = time - (timeval->tv_sec * 1000000);
}

void	calc_elapsed(struct timeval *elapsed)
{
  struct timeval	tmp;

  x_int(-1, gettimeofday(&tmp, NULL), "gettimeofday");
  if (tmp.tv_usec < elapsed->tv_usec)
    {
      elapsed->tv_usec = (tmp.tv_usec + 1000000) - elapsed->tv_usec;
      elapsed->tv_sec = (tmp.tv_sec - 1) - elapsed->tv_sec;
    }
  else
    {
      elapsed->tv_usec = tmp.tv_usec - elapsed->tv_usec;
      elapsed->tv_sec = tmp.tv_sec - elapsed->tv_sec;
    }
}
